/**
 * Created by hren on 17/1/18.
 * Style基础组件,使样式自适应各种尺寸屏幕
 * 1、自动转换StyleSheet中px值
 * 2、render内样式，使用借口dp转换
 * 使用示例：
 * import {StyleSheet, dp} from 'FStyleSheet'
 * 1、StyleSheet.creat({样式})
 * 2、<View style={{width: dp(20)}} />
 */
import react, { Component } from 'react';
import { StyleSheet, Dimensions } from 'react-native';

const { width } = Dimensions.get('window');
let designWidth;
const REG_ARR = [
    /^margin/,
    /^padding/,
    /width$/i,
    /height/,
    /top/,
    /bottom/,
    /left/,
    /right/,
    /radius$/i,
    /^translate/,
    /fontSize/,
    /lineHeight/,
];

function setDesignWidth(val) {
    designWidth = val || 750;
}

function px2dp(px, key) {
    if (typeof px !== 'number') return px;
    if(Math.abs(px) <= 1) return px;
    !designWidth && (designWidth = 750);
    return key === 'lineHeight' ? Math.round(parseInt(px) * width / designWidth)
        : parseInt(px) * width / designWidth;
}

function transformStyles(val, key) {
    if (Array.isArray(val)) {
        let res = [];
        val.forEach(item => res.push(transformStyles(item)));
        return res;
    }

    if (Object.prototype.toString.call(val) === '[object Object]') {
        for (let i in val) val[i] = transformStyles(val[i], i);
    }

    REG_ARR.forEach((regItem) => {
        if (regItem.test(key)) {
            val = px2dp(val, key);
        }
    })

    return val;
}

class FStyleSheet {
    static create(obj, size) {
        let preSize = designWidth;
        size && setDesignWidth(size);
        let styles = transformStyles(obj);
        setDesignWidth(preSize);
        return StyleSheet.create(styles);
    }
}

export {
    FStyleSheet as StyleSheet,
    px2dp as dp,
    setDesignWidth as setDesignWidth,
}